#!/usr/bin/env python3
# coding: utf-8
# Copyright 2024 Huawei Technologies Co., Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
# ===========================================================================
import os
import platform
import glob
import json
from ansible.module_utils import common_utils
from ansible.module_utils.basic import AnsibleModule


class vLLM_Ascend_Uninstaller:

    def __init__(self):
        self.module = AnsibleModule(
            argument_spec=dict(
                tags=dict(type="list", required=True),
            )
        )
        self.run_tags = self.module.params["tags"]
        self.messages = [] 

    def _module_failed(self):
        """失败时返回日志信息"""
        return self.module.fail_json(msg="\n".join(self.messages), rc=1, changed=False)

    def _module_success(self):
        """成功时返回日志信息"""
        return self.module.exit_json(msg="Uninstall vLLM Ascend container success.", rc=0, changed=True)

    def _check_docker_env(self):
        """检查Docker环境"""
        self.messages.append("[ASCEND] Checking Docker environment...")
        
        # 检查Docker是否安装
        docker_path = self.module.get_bin_path("docker", required=False)
        if not docker_path:
            self.messages.append("[ASCEND][ERROR] Docker not installed, please install docker first.")
            self._module_failed()
        self.messages.append("[ASCEND] Docker is installed at: {}".format(docker_path))
        
        return docker_path

    def run(self):
        try:
            self._check_docker_env()
            common_utils.stop_and_rm_container(self.module, "vllm_ascend")
        except Exception as e:
            self.messages.append(str(e))
            self._module_failed()
        self._module_success()


def main():
    vLLM_Ascend_Uninstaller().run()


if __name__ == "__main__":
    main()